package com.base.library.utils

import android.view.View
import android.view.View.OnClickListener
import java.util.*

/**
 * 方便的防连点工具
 */
class FastClickUtil {
    companion object {
        private val mViews: WeakHashMap<View, Long> by lazy { WeakHashMap() }
        private var mCommonClickTime: Long = 0
        var INTERVAL = 500

        @JvmStatic
        fun View.click(onClickListener: OnClickListener) {
            this.setOnClickListener {
                if (canHandleClick()) {
                    onClickListener.onClick(it)
                }
            }
        }

        /**
         * 是否需要响应这次的连点
         */
        @JvmStatic
        fun View.canHandleClick(): Boolean {
            val currentTimeMillis = System.currentTimeMillis()
            mCommonClickTime = currentTimeMillis
            val savedTime = mViews[this]
            if ((savedTime == null) || (currentTimeMillis - savedTime > INTERVAL)) {
                mViews[this] = currentTimeMillis
                return true
            }
            return false
        }

        /**
         * 是否需要响应这次的连点 公用cd
         */
        @JvmStatic
        fun canHandleClickCommon(): Boolean {
            val currentTimeMillis = System.currentTimeMillis()
            val deltaTime = currentTimeMillis - mCommonClickTime
            mCommonClickTime = currentTimeMillis
            return deltaTime > INTERVAL
        }
    }
}